import type { FC, ReactNode } from 'react'
import { memo, useState } from 'react'
import styles from './index.less'
import { setCookie } from '@/utils'
import { API } from '@/api'
import crypto from 'crypto'
import { message } from 'antd'
import { useModel } from 'umi'

interface TProps {
  children?: ReactNode
}

const DingLogin: FC<TProps> = () => {
  console.log(window.location.origin)
  const { setClientId, clientId, setUserPermissions, setUserName } = useModel('userModel')
  const [loginData, setLoginData] = useState({} as any)
  const handelLogin = () => {
    // STEP3：在需要的时候，调用 window.DTFrameLogin 方法构造登录二维码，并处理登录成功或失败的回调。
    window.DTFrameLogin(
      {
        id: 'self_defined_element',
        width: 300,
        height: 300,
      },
      {
        // redirect_uri: encodeURIComponent('https://login.techxiaoma.com/api/uusc/user/auth'),
        redirect_uri: encodeURIComponent(window.location.origin),
        client_id: 'ding22jlkdzuk0sdk0mz',
        scope: 'openid',
        response_type: 'code',
        state: '12345678',
        prompt: 'consent',
      },
      async (loginResult: any) => {
        const { redirectUrl, authCode, state } = loginResult
        // 这里可以直接进行重定向
        // http://uusc.techxiaoma.com:8080/uusc/user/auth?authCode=96648c5cdd5534c886ae420139b88941&state=12345678
        // window.location.href = `http://uusc.techxiaoma.com:8080/uusc/user/auth?authCode=${authCode}&state${state}`

        // fetch(`${process.env.DING_LOGIN}uusc/user_info/login?authCode=${authCode}&state${state}`)
        //   .then((response) => {
        //     if (response.ok) {
        //       return response.json()
        //     }
        //     throw new Error('Network response was not ok.')
        //   })
        //   .then((data) => {
        //     // 处理获取到的数据
        //     console.log(data, '数据')
        //   })
        // 也可以在不跳转页面的情况下，使用code进行授权
        console.log(loginResult)
        console.log(loginResult.authCode)
        const res = await API.userLogin({
          data: { identityType: '2', authCode: loginResult.authCode },
          getResponse: true,
        })
        console.log(res)
        // 设置clientid与权限
        setClientId(res.headers.clientid)
      },
      (errorMsg: any) => {
        // 这里一般需要展示登录失败的具体原因
        console.log(`Login Error: ${errorMsg}`)
      }
    )
  }

  const handelSetCookie = () => {
    setCookie('test', '123456', 1000, 'techxiaoma.com', '/')
    console.log(document.cookie)
  }

  const login = async () => {
    if (!loginData.username || !loginData.password) {
      message.error('请输入账号密码')
      return
    }
    let md5 = crypto.createHash('md5')
    md5.update(loginData.password)
    const password = md5.digest('hex')
    const res = await API.userLogin({
      data: { username: loginData.username, password, identityType: '1' },
      getResponse: true,
    })
    console.log(res, '!!!')
    // 设置clientid与权限
    setClientId(res.headers.clientid)
  }
  return (
    <div
      className={styles.dingLogin}
      id="dingLogin"
    >
      <h2>dingLogin</h2>
      <div
        id="self_defined_element"
        className={styles.selfDefined}
      ></div>
      <button
        type="button"
        onClick={handelLogin}
      >
        登录
      </button>
      <button
        type="button"
        onClick={handelSetCookie}
      >
        设置cookie
      </button>
      <span>账号</span>
      <input
        type="text"
        value={loginData.username}
        onChange={(e) => setLoginData({ ...loginData, username: e.target.value })}
      />
      <span>密码</span>
      <input
        type="text"
        value={loginData.password}
        onChange={(e) => setLoginData({ ...loginData, password: e.target.value })}
      />
      <button
        type="button"
        onClick={login}
      >
        登录
      </button>
    </div>
  )
}

export default memo(DingLogin)
